package com.shanghaionstar.activity.webview.handler;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.network.ClientTraceInstance;
import com.onstar.cn.framework.network.NoSSLv3SocketFactory;
import com.onstar.cn.mag.publicService.response.H5DispatcherResEntity;
import com.onstar.cn.mag.publicService.response.PreferentialResEntity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BannerUtil;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by Yonglang Hong on 2017/2/9.
 */
public class CheYinInsuranceHandler extends DefaultWebHandler {

    //    String url = "https://nisp.zhangshangxian.cn/app/auth/10000001?source=onstar&business_type=appointmentRegistration&signature=4e09471e7fe8723fb9a3afa7cf94fb17286cdde2619846f0a0b243037cc150c2";
    String body = "{\"userName\":\"cnlyml\",\"vehicleID\":\"Vewerewerwere\",\"timestamp\":\"111111111\",\"licensePlate\":\"京ACD028\",\"engineNumber\":\"sdfsdfaf\",\"mobilePhoneNumber\":\"18080371159\",\"lastName\":\"张\",\"location\":{\"longitude\":\"121.50\",\"latitude\":\"31.253207\"},\"firstName\":\"三\",\"emailAddress\":\"test@shanghaionstar.com\",\"extensions\":[{\"value\":\"Buick\",\"code\":\"Make\"},{\"value\":\"Enclave\",\"code\":\"Model\"}]}";
    final static String TAG = CheYinInsuranceHandler.class.getSimpleName();

    private static final String DEFAULT_USER_AGENT_PHONE = "Mozilla/5.0 (Linux; U; "
            + "Android 4.4.2; en-us; Xoom Build/HMJ25) AppleWebKit/534.13 "
            + "(KHTML, like Gecko) Version/4.0 Safari/534.13";
    public static final String DEFAULT_USER_AGENT_PC = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:38.0) Gecko/20100101 Firefox/38.0";

    // avoid java.lang.StackOverflowError.
    private AtomicInteger mStackDeep = new AtomicInteger(15);

    public static final String PARAM_BODY = "body";

    public static final String ENTITY = "entity";

    List<String> cookies = null;

    private String errPageLink;

    private WebViewPhotoHandler webViewPhotoHandler;

    private Subscription subscription;
    private String url;
    CommonWebViewActivity mActivity;

    public CheYinInsuranceHandler(Context context) {
        super(context);
    }


    @Override
    public void handMsg(Message msg) {
        switch (msg.what) {
            case IWebType.TYPE_CHE_YIN_INSURANCE:
                init(msg);
                break;
        }
    }

    private void init(Message msg) {
        if (context instanceof CommonWebViewActivity) {
            mActivity = (CommonWebViewActivity) context;
            Bundle bundle = mActivity.getBundle();
            PreferentialResEntity entity = (PreferentialResEntity) bundle.getSerializable(IWebType.KEY_SERIAL_DATA);
            WebView webView = mActivity.getWebview();
            loadBodyAndShowWebContent(entity, mActivity, webView);
            webViewPhotoHandler = new WebViewPhotoHandler(CheYinInsuranceHandler.this, mActivity);
        }
    }

    /**
     * webViewPhotoHandler处理web图片上传
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        webViewPhotoHandler.onActivityResult(requestCode, resultCode, data);
    }

    private void loadBodyAndShowWebContent(PreferentialResEntity entity, final CommonWebViewActivity activity, final WebView webView) {
        if (entity == null) {
            showErrPage(activity, webView);
            return;
        }
        activity.setLoading(true);
        BannerUtil bannerUtil = new BannerUtil(activity);
        subscription = bannerUtil.h5Dispatcher(entity).subscribeOn(activity.getScheduler().backgroundThread())
                .observeOn(activity.getScheduler().mainThread()).subscribe(new Action1<H5DispatcherResEntity>() {
                    @Override
                    public void call(H5DispatcherResEntity mResult) {
                        String url = mResult.getUrl();
                        String body = mResult.getJsonStr();
                        if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(body)) {
                            CheYinInsuranceHandler.this.body = body;
                            CheYinInsuranceHandler.this.url = url;
                            showWebContent(activity);
                        } else {
                            showErrPage(activity, webView);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //抛出Error异常
                        showErrPage(activity, webView);
                    }
                });

    }

    private void showWebContent(Context activity) {
        setBody(activity);
        new NetPost().execute();
    }

    private void showErrPage(Context activity, WebView webView) {
        if (TextUtils.isEmpty(errPageLink))
            errPageLink = Constants.CURRENT_PREFIX_H5_URL + Constants.WEB_ERR_LINK_ZH;
        webView.loadUrl(errPageLink);
    }

    private void setBody(Context activity) {
//        body = "{\"userName\":\"USERNAME\",\"vehicleID\":\"VEHICLEID\"," +
//                "\"licensePlate\":\"沪A12345\",\"engineNumber\":\"NT12345\",\"mobilePhoneNumber\":\"MOBILEPHONENUMBER\"," +
//                "\"emailAddress\":\"EMAILADDRESS\",\"firstName\":\"吉星\",\"lastName\":\"安\"," +
//                "\"location\":{\"longitude\":121.609824,\"latitude\":31.253207}," +
//                "\"timestamp\":1462432102976," +
//                "\"extensions\":[{\"code\":\"Make\",\"MAKE\":\"Buick\"},{\"code\":\"Model\",\"value\":\"MODEL\"}]}";
//        body = body.replace("USERNAME", ApplicationUtil.getInstance().getIdpID());
//        body = body.replace("VEHICLEID", ApplicationUtil.getInstance().getVin();
//        body = body.replace("MOBILEPHONENUMBER", ApplicationUtil.getInstance().getMobile());
//        body = body.replace("EMAILADDRESS", ApplicationUtil.getInstance().getEmail());
        if (ApplicationUtil.getInstance().getCurrentVehicle() != null) {
            body = body.replace("MAKE", ApplicationUtil.getInstance().getCurrentVehicle().getMake());
            body = body.replace("MODEL", ApplicationUtil.getInstance().getCurrentVehicle().getModel());
        }
        LogManager.getInstance().d("the cheyin request body model is ==========>>" + body);
    }

    @SuppressLint("NewApi")
    public void synCookies(String url) {
        try {
            Log.d("syncCookie.url", url);
            CookieSyncManager.createInstance(mActivity.getApplicationContext());
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            String oldCookie = cookieManager.getCookie(url);
            if (oldCookie != null) {
                Log.d("CookieOutter.oldCookie", oldCookie);
            }

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                cookieManager.removeSessionCookies(new ValueCallback<Boolean>() {
                    @Override
                    public void onReceiveValue(Boolean value) {
                    }
                });
            } else {
                cookieManager.removeSessionCookie();
            }

            /**
             * setCookie 只能识别分号前面的键值对，所以需要多个设置
             */
            if (cookies != null && !cookies.isEmpty()) {
                for (String cookie : cookies)
                    cookieManager.setCookie(url, cookie);
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                cookieManager.flush();
            } else {
                CookieSyncManager.getInstance().sync();
            }
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                Log.d("syncCookie.newCookie", newCookie);
            }
        } catch (Exception e) {
            Log.e("syncCookie failed", e.toString());
        }
    }


    class NetPost extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mActivity.setLoading(true);
        }

        @SuppressLint("NewApi")
        @Override
        protected String doInBackground(Void... params) {
            try {
                String u = recursiveTracePath(url, null);
                return u;
            } catch (Exception e) {
                Log.e("err", e.getMessage());
                return null;
            }
        }

        @Override
        protected void onPostExecute(final String result) {
            if (result != null) {
                Log.e("result", result);
            } else {
                showErrPage(mActivity, mActivity.getWebview());
                return;
            }
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    synCookies(result);
                    setWebChromeClient();
                    mActivity.getWebview().loadUrl(result);
                }
            });
        }
    }

    private void setWebChromeClient() {
        if (mActivity != null) {
            mActivity.getWebview().setWebChromeClient(webViewPhotoHandler.getChromeClient());
        }
    }

    public String recursiveTracePath(String path, String reffer) throws Exception {
        String realURL = null;
        if (mStackDeep.getAndDecrement() > 0) {// 避免异常递归导致StackOverflowError
            URL url = null;
            HttpURLConnection conn = null;
            try {
                url = new URL(path);

                if (path.contains("https")) {
                    SSLContext sslcontext = SSLContext.getInstance("TLSv1");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory());
                    HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory);
                    conn = (HttpsURLConnection) url.openConnection();
                } else {
                    conn = (HttpURLConnection) url.openConnection();
                }
                conn = (HttpURLConnection) url.openConnection();

                conn.setRequestProperty("Content-type", "application/json");
                conn.setRequestMethod("POST");

                StringBuffer sBuffer = new StringBuffer();
                if (cookies != null) {
                    for (String cookie : cookies) {
                        sBuffer.append(cookie + ",");
                    }
                }
                conn.setRequestProperty("Cookie", sBuffer.toString());
                conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT_PHONE);
                conn.addRequestProperty(Constants.CLIENT_TRACE_ID, ClientTraceInstance.getInstance().getClientTraceId());
                conn.getOutputStream().write(body.getBytes());
                conn.setConnectTimeout(30000);
                conn.setReadTimeout(30000);
                conn.setInstanceFollowRedirects(false);
                int code = conn.getResponseCode();// network block
                if (conn.getHeaderFields() != null
                        && conn.getHeaderFields().get("Set-Cookie") != null
                        && conn.getHeaderFields().get("Set-Cookie").size() > 0) {
                    cookies = conn.getHeaderFields().get("Set-Cookie");
                    if (cookies != null && !cookies.isEmpty()) {
                        for (String cookie : cookies)
                            Log.e("cookie", cookie);
                    }
                }
                if (needRedirect(code)) {
                    // 临时重定向和永久重定向location的大小写有区分
                    String location = conn.getHeaderField("Location");
                    if (location == null) {
                        location = conn.getHeaderField("location");
                    }

                    if (location == null) {
                        return recursiveTracePath(path, path);
                    }

                    if (!(location.startsWith("http://") || location.startsWith("https://"))) {
                        // 某些时候会省略host，只返回后面的path，所以需要补全url
                        URL origionUrl = new URL(path);
                        location = origionUrl.getProtocol() + "://" + origionUrl.getHost() + location;
                    }
                    Log.e("302 url", location);
                    return recursiveTracePath(location, path);
                } else {
                    // redirect finish.

                    // InputStream in = conn.getInputStream();
                    // InputStreamReader isr = new InputStreamReader(in,
                    // "utf-8");
                    // BufferedReader reader = new BufferedReader(isr);
                    // String line = null;
                    // while ((line = reader.readLine()) != null) {
                    // web += line;
                    // }

                    realURL = path;
                }

            } catch (Exception e) {
//                e.printStackTrace();
                Log.w(TAG, e.toString());
                throw e;
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
            }
        }
        return realURL;
    }

    private boolean needRedirect(int code) {
        // 301,302,303,307
        Log.e("code", code + "");
        return (code == 301 || code == 302 || code == 303 || code == 307);
    }

    class MyWebviewCient extends WebViewClient {
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//            synCookies(url);
            WebResourceResponse response = null;
            response = super.shouldInterceptRequest(view, url);
            return response;
        }
//        @SuppressLint("NewApi")
//        @Override
//        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//            String url = request.getUrl().toString();
////            synCookies(url);
//            final Map<String,String> requestHead =  request.getRequestHeaders();//拿到头
//            return super.shouldInterceptRequest(view, new WebResourceRequest() {
//                @Override
//                public Uri getUrl() {
//                    return null;
//                }
//
//                @Override
//                public boolean isForMainFrame() {
//                    return false;
//                }
//
//                @Override
//                public boolean hasGesture() {
//                    return false;
//                }
//
//                @Override
//                public String getMethod() {
//                    return null;
//                }
//
//                @Override
//                public Map<String, String> getRequestHeaders() {
//                    return requestHead;
//                }
//            });
//        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//            handler.proceed();
//            activity.showFailWebView();
            showErrPage(mActivity, view);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                try {
                    mActivity.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                } catch (Exception e) {
                    LogManager.getInstance().e(e.getMessage());
                    AlertDialogUtil.showAlertDialog(mActivity, "", "未检测到支付宝客户端，请安装后重试。", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mActivity.startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://d.alipay.com")));
                        }
                    });
                }
            } else if (url.startsWith("tel:")) {
                mActivity.requestRunTimePermissions(new String[]{Manifest.permission.CALL_PHONE}, new PermissionCall() {
                    @Override
                    public void requestSuccess() {
                        Uri uri = Uri.parse(url);
                        Intent intent = new Intent(Intent.ACTION_CALL, uri);
                        mActivity.startActivity(intent);
                    }

                    @Override
                    public void refused() {

                    }
                });

            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//            activity.showFailWebView();
            showErrPage(mActivity, mActivity.getWebview());
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d("WebView", "onPageStarted " + url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (view != null) {
                mActivity.getTop_layout().setTopTitle(view.getTitle());
            }
        }
    }


}
